# Simple HarmonyOS Deployment Script with Debug

# Configuration
$BUNDLE_NAME = "com.example.landscapeportraittoggle"
$ABILITY_NAME = "EntryAbility"
$LOG_FILE = "deploy_log.txt"

# Clear previous log
Clear-Content -Path $LOG_FILE -ErrorAction SilentlyContinue

function Log-Message($message) {
    Write-Host $message
    Add-Content -Path $LOG_FILE -Value $message
}

Log-Message "Starting HarmonyOS App Build and Deploy at $(Get-Date)"
Log-Message ""

# Check device connection
Log-Message "1. Checking device connection..."
try {
    $devices = hdc list targets 2>&1
    Log-Message "Devices: $devices"
    
    if ([string]::IsNullOrWhiteSpace($devices)) {
        Log-Message "Error: No device found!" 
        exit 1
    }
    Log-Message "Device connected successfully"
} catch {
    Log-Message "Error checking device: $_"
    exit 1
}

# Clean build directories
Log-Message "\n2. Cleaning build directories..."
try {
    if (Test-Path "entry\build") {
        Log-Message "Removing entry\build..."
        Remove-Item -Path "entry\build" -Recurse -Force -ErrorAction Stop
    }
    if (Test-Path "build") {
        Log-Message "Removing build..."
        Remove-Item -Path "build" -Recurse -Force -ErrorAction Stop
    }
    Log-Message "Cleanup completed"
} catch {
    Log-Message "Error during cleanup: $_"
}

# Build project
Log-Message "\n3. Building project..."
Log-Message "Running: hvigorw assembleApp"
try {
    # Capture both stdout and stderr
    $buildOutput = hvigorw assembleApp 2>&1
    $exitCode = $LASTEXITCODE
    
    # Log the build output
    foreach ($line in $buildOutput) {
        Log-Message "BUILD: $line"
    }
    
    if ($exitCode -ne 0) {
        Log-Message "Build failed with exit code: $exitCode"
        exit 1
    }
    Log-Message "Build completed successfully"
} catch {
    Log-Message "Exception during build: $_"
    exit 1
}

# Find HAP file in common locations
Log-Message "\n4. Finding HAP file..."
$hapLocations = @(
    "entry\build\default\outputs\default",
    "entry\build\outputs",
    "build"
)

$foundHaps = @()
foreach ($location in $hapLocations) {
    Log-Message "Checking $location..."
    if (Test-Path $location) {
        try {
            $haps = Get-ChildItem -Path $location -Filter "*.hap" -Recurse -ErrorAction SilentlyContinue
            if ($haps.Count -gt 0) {
                foreach ($hap in $haps) {
                    Log-Message "Found: $($hap.FullName)"
                    $foundHaps += $hap.FullName
                }
            }
        } catch {
            Log-Message "Error searching ${location}: $_"
        }
    }
}

if ($foundHaps.Count -eq 0) {
    Log-Message "Error: No HAP files found!"
    exit 1
}

$hapFile = $foundHaps[0]
Log-Message "Using HAP file: $hapFile"

# Install app
Log-Message "\n5. Installing app..."

# Uninstall existing app
try {
    Log-Message "Uninstalling existing app..."
    $uninstallOutput = hdc shell bm uninstall $BUNDLE_NAME 2>&1
    Log-Message "Uninstall output: $uninstallOutput"
} catch {
    Log-Message "Error during uninstall: $_"
}

# Install new app
try {
    Log-Message "Sending HAP file to device..."
    $sendOutput = hdc file send $hapFile /data/local/tmp/ 2>&1
    Log-Message "Send output: $sendOutput"
    
    if ($LASTEXITCODE -ne 0) {
        Log-Message "Failed to send HAP file"
        exit 1
    }
    
    $hapName = Split-Path -Leaf $hapFile
    Log-Message "Installing $hapName..."
    $installOutput = hdc shell bm install -p /data/local/tmp/$hapName 2>&1
    Log-Message "Install output: $installOutput"
    
    if ($LASTEXITCODE -ne 0) {
        Log-Message "Install failed!"
        exit 1
    }
    Log-Message "Install completed successfully"
} catch {
    Log-Message "Exception during install: $_"
    exit 1
}

# Start app
Log-Message "\n6. Starting app..."
try {
    $startOutput = hdc shell aa start -a $ABILITY_NAME -b $BUNDLE_NAME 2>&1
    Log-Message "Start output: $startOutput"
    
    if ($LASTEXITCODE -eq 0) {
        Log-Message "App started successfully"
    } else {
        Log-Message "Warning: App start returned non-zero exit code, but may have been installed successfully"
    }
} catch {
    Log-Message "Exception during app start: $_"
}

Log-Message "\nDeployment process completed!"
Log-Message "Check log file: $LOG_FILE for details"